import React from "react";
import BaseComponent from "../../redare/components/BaseComponent";
import {Card, Image, PageHeader, Input, Radio, Select, Checkbox, Tree, Row, Col, Tabs, Form, Button} from "antd";
import OnlFormHeadForm from "../../components/onlformhead/OnlFormHeadForm";
import OnlFormHeadPresenter from "../../.gen/presenter/OnlFormHeadPresenter";
import {WebPage} from "../../redare_components/webplatform_workbench/utils/WorkbenchDecoratorUtil";
import OnlFormHeadGrid from "../../components/onlformhead/OnlFormHeadGrid";
import DirectoryTree from "../../components/common/DirectoryTree";
import GenPathForm from "../../components/onlformhead/GenPathForm";
import CodeMirror from '@uiw/react-codemirror';
import Zmage from "react-zmage";
import {javascript} from '@codemirror/lang-javascript';

const routes = [
    {
        path: '/',
        breadcrumbName: '首页',
    },
    {
        path: '/onlformhead/manager',
        breadcrumbName: '',
    }
];

const onlFormHeadForm = 'OnlFormHeadForm';
const sqlForm = 'sqlForm';
const codeGenForm = 'codeGenForm';
const selectDirForm = 'selectDirForm';
const pathForm = 'pathForm';
const previewForm = 'previewForm';


export default @WebPage({
    id: 'com.redare.devframework.webplatform.pages.onlformhead.OnlFormHeadPage',
    name: '表单管理',
    webPath: '/onlformhead/manager',
    webFunIds: [
        'OnlFormHeadAdd',
        'OnlFormHeadEdit',
        'OnlFormHeadDelete'
    ]
})

class OnlFormHeadPage extends BaseComponent {

    searchForm = React.createRef();

    constructor(props) {
        super(props);
        this.state = {
            codeRoots: [],
            genTables: [],
            previewCode: '',
            visible: false,
            syncLoading: false,
            previewTable: undefined,
            currentCodeRoot: undefined
        }
        this.presenter = new OnlFormHeadPresenter(this);
    }


    _onReset() {
        this.searchForm.current.resetFields()
    }

    _onSearch(values,page) {
        this._form.searchValues = values;
        this.grid._findOnlFormHeadPage(values, page);
    }


    _onAdd() {
        delete this._form.dataId
        this.showModal(onlFormHeadForm);
    }

    _onFormBtnClick(event) {
        this.showModal(sqlForm)
    }


    _submitModalForm = () => {
        if (this.form) {
            this.form.validateFormFields().then((values) => {
                this.showDoingIndicator();
                if (this._form.dataId) {
                    values.id = this._form.dataId;
                    this.presenter.editOnlFormHead(values);
                    return;
                }
                this.presenter.addOnlFormHead(values);
            });
        }
    }

    _submitSqlModalForm = () => {
        this.setModalConfirmLoading(sqlForm, true)
        this.presenter.parseSqlToOnlFormHead({sysId: this._urlQuery.id, sql: this.state.text}, undefined, () => {
            this.closeModal(sqlForm)
            this._onSearch();
        }, () => {
            this.setModalConfirmLoading(sqlForm, false)
        });
    }

    _submitCodeGenModalForm = () => {
        this.setModalConfirmLoading(codeGenForm, true)
        const {genTables, currentCodeRoot} = this.state;
        let groups = [];
        if (currentCodeRoot) {
            groups = currentCodeRoot.groups;
        }
        if (groups.length === 0) {
            this.toastFail('请选择要生成的模板')
            return;
        }
        let groupIds = [];
        let groupPathMap = {};
        groups.forEach((value, index) => {
            if (value.checked) {
                groupIds.push(value.id)
                groupPathMap[value.id] = value.outputPath + value.basePackage;
            }
        })
        this.presenter.codeGenerate({
            onlFormHeads: genTables,
            groupIds: groupIds,
            groupPathMap: groupPathMap
        }, undefined, () => {
            this.closeModal(codeGenForm)
            this.toastSuccess('代码生成成功')
        }, () => {
            this.setModalConfirmLoading(codeGenForm, false)
        });
    }

    _onEdit(id) {
        if (id) {
            this.showModal(onlFormHeadForm)
            this._form.dataId = id;
            this.showSpin()
            this.presenter.getOnlFormHead({id}, {}, (result) => {
                if (result && this.form) {
                    this.form.setFormData(result.data)
                }
            })
        }
    }

    _handleGridBtnClick = (type, records) => {
        if (type === 'gen') {
            this.setState({genTables: records, previewTable: undefined});
            this.showModal(codeGenForm);
            this.presenter.getCodeRoots({}, (result) => {
                this.setState({
                    codeRoots: result.data,
                    selectValue: result.data[0].id,
                    currentCodeRoot: result.data[0]
                });
            })
        } else if (type === 'preview') {
            this.setState({previewTable: records[0], genTables: []});
            this.showModal(previewForm);
            this.presenter.getCodeRoots({}, (result) => {
                this.setState({
                    codeRoots: result.data,
                    selectValue: result.data[0].id,
                    currentCodeRoot: result.data[0]
                });
            })
        } else if (type === 'sync') {
            this.presenter.syncSqlToOnlFormHead({}, (result) => {
                if (result) {
                    this.grid._findOnlFormHeadPage();
                }
            })
        }
    }

    _onEditOnlFormHeadSuccess() {
        this._onAddOnlFormHeadSuccess();
    }

    _onAddOnlFormHeadSuccess() {
        this._onSearch();
        if (this.form) {
            this.form.resetFormFields()
        }
        this.closeModal(onlFormHeadForm);
    }


    onTextChange = ({target: {value}}) => {
        this.setState({text: value});
    };


    handleSelectChange = (value, option) => {
        this.setState({selectValue: value, currentCodeRoot: option.data});
    };

    onCodeGenCheckChange = (e) => {
        let data = e.target.data;
        let checked = e.target.checked;
        this.currentCheckItem = data;
        let {currentCodeRoot, genTables, previewTable} = this.state;
        data.checked = checked;
        if (checked) {
            this.showModal(pathForm);
            this.presenter.getCodeGroupGenPath({id: data.id, name: data.name}, null, (result) => {
                if (this.pathForm) {
                    this.pathForm.setFormData(result.data)
                }
            })
        }
        this.setState(currentCodeRoot);
    }

    onPreviewCheckChange = (e) => {
        let data = e.target.data;
        let value = e.target.value;
        this.currentCheckItem = data;
        let {currentCodeRoot, genTables, previewTable} = this.state;
        if (value) {
            this.presenter.codePreview({onlFormHead: previewTable, templateId: data.id}, null, (result) => {
                if (result && result.data) {
                    this.setState({
                        // previewCode: window.js_beautify(result.data),
                        previewCode: result.data,
                        radioValue: value
                    })
                }
            });
        }
    }

    setVisible(visible) {
        this.setState(visible)
    }

    onInputChange(index, field, e) {
        const {value} = e.target;
        let {genTables} = this.state;
        genTables[index]['' + field] = value;
        this.setState({genTables})

    }

    render() {
        let currentCodeRoot = this.state.currentCodeRoot;
        let groups = [];
        if (currentCodeRoot) {
            groups = currentCodeRoot.groups;
        }
        let {genTables, activeKey, previewTable, visible} = this.state;
        let tableName = '';
        if (previewTable) {
            tableName = previewTable.tableName;
        }
        return (
            <div>
                {/*<PageHeader className="margin-bottom bg-white" title="列表" routes={routes} onBack={(e => {*/}
                {/*    this.routeBack(this.props.history);*/}
                {/*})}/>*/}
                {/*<Card bordered={false} className="margin24">*/}
                {/*    <OnlFormHeadSearchForm*/}
                {/*        onFormBtnClick={this._onFormBtnClick.bind(this)}*/}
                {/*        onSearchBtnClick={this._onSearch.bind(this)} onAddBtnClick={this._onAdd.bind(this)}/>*/}
                {/*</Card>*/}

                <Card bordered={false}  style={{ position: 'fixed', zIndex: 100,top:0, width: '100%' }}>
                    <Row gutter={4}>
                        <Col>
                            <Button key="button" type="primary" onClick={() => {
                                let data = this.grid.getData();
                                let selectedRowKeys = this.grid.getSelectRows();

                                if (!selectedRowKeys) {
                                    return;
                                }
                                let records = [];
                                for (let i = 0; i < data.length; i++) {
                                    selectedRowKeys.forEach((value, index) => {
                                        if (data[i].id === value) {
                                            records.push(data[i]);
                                        }
                                    })
                                }
                                this.setState({genTables: records, previewTable: undefined});
                                this.showModal(codeGenForm);
                                this.presenter.getCodeRoots({}, (result) => {
                                    this.setState({
                                        codeRoots: result.data,
                                        selectValue: result.data[0].id,
                                        currentCodeRoot: result.data[0]
                                    });
                                })
                            }}>
                                代码生成
                            </Button>
                        </Col>
                        <Col>
                            <Button key="button" type="primary" onClick={() => {
                                let data = this.grid.getData();
                                let selectedRowKeys = this.grid.getSelectRows();
                                if (!selectedRowKeys || selectedRowKeys.length > 1) {
                                    this.toastFail('请选择一条数据操作');
                                    return;
                                }
                                let records = [];
                                for (let i = 0; i < data.length; i++) {
                                    selectedRowKeys.forEach((value, index) => {
                                        if (data[i].id === value) {
                                            records.push(data[i]);
                                        }
                                    })
                                }
                                this.setState({previewTable: records[0], genTables: []});
                                this.showModal(previewForm);
                                this.presenter.getCodeRoots({}, (result) => {
                                    this.setState({
                                        codeRoots: result.data,
                                        selectValue: result.data[0].id,
                                        currentCodeRoot: result.data[0]
                                    });
                                })
                            }}>
                                预览
                            </Button>
                        </Col>
                        <Col>
                            <Button key="button" type="primary" onClick={() => {
                                this.showModal(sqlForm)
                            }}>
                                导入
                            </Button>
                        </Col>
                        <Col>
                            <Button key="button" loading={this.state.syncLoading} type="primary" onClick={() => {
                                this.setState({syncLoading: true})
                                this.presenter.syncSqlToOnlFormHead({}, (result) => {
                                    this.setState({syncLoading: false})
                                    if (result) {
                                        this.grid._findOnlFormHeadPage();
                                    }
                                }, () => {
                                    this.setState({syncLoading: false})
                                })
                            }}>
                                同步
                            </Button>
                        </Col>
                        <Col>
                            <Input.Search placeholder="表名/表说明"
                                          allowClear={true}
                                          onSearch={(value)=>{
                                if(this.grid){
                                    this.grid._findOnlFormHeadPage({key:value},1);
                                }
                            }}  />
                        </Col>
                    </Row>
                </Card>
                <Card bordered={true} style={{marginTop:80}}>
                    <OnlFormHeadGrid ref={(o) => {
                        this.grid = o
                    }}
                                     onFormBtnClick={this._onFormBtnClick.bind(this)}
                                     handleBtnClick={this._handleGridBtnClick}
                                     onItemEdit={this._onEdit.bind(this)}
                    />
                </Card>
                {this.renderModal(onlFormHeadForm,
                    <OnlFormHeadForm ref={(o) => {
                        this.form = o
                    }}/>, {
                        title: '编辑',
                        props: {width: '100%', bodyStyle: {maxHeight: 580, overflow: 'auto'}},
                        okHandler: this._submitModalForm
                    })}

                {this.renderModal(sqlForm, this.renderSpin(<Input.TextArea
                    value={this.state.text}
                    scroll={true}
                    placeholder={'粘贴sql建表语句'}
                    autoSize={{minRows: 4, maxRows: 8}}
                    onChange={this.onTextChange}/>), {
                    title: 'sql解析',
                    okHandler: this._submitSqlModalForm
                })}


                {this.renderModal(codeGenForm, this.renderSpin(
                    <>
                        <Tabs
                            onChange={this.onChange}
                            activeKey={activeKey}
                        >
                            {genTables.map((pane,index)=> (
                                <Tabs.TabPane tab={pane.tableName} key={pane.tableName} closeable={false}>
                                    <Form labelCol={{span: 2}}>
                                        <Row gutter={[24, 24]}>
                                            <Col span={24}>
                                                <Form.Item
                                                    label="实体名称"
                                                    rules={[{required: true, message: '请输入表名'}]}>
                                                    <Input
                                                        onChange={this.onInputChange.bind(this, index, 'model')}
                                                        value={pane.model} placeholder="请输入表名" maxLength="50"/>
                                                </Form.Item>
                                            </Col>
                                            <Col span={24}>
                                                <Form.Item
                                                    label="表名"
                                                    rules={[{required: true, message: '请输入表名'}]}
                                                >
                                                    <Input
                                                        onChange={this.onInputChange.bind(this, index, 'tableName')}
                                                        value={pane.tableName} placeholder="请输入表名" maxLength="50"/>
                                                </Form.Item>
                                            </Col>
                                            <Col span={24}>
                                                <Form.Item
                                                    label="表说明"
                                                    rules={[{required: true, message: '请输入表说明'}]}
                                                >
                                                    <Input
                                                        onChange={this.onInputChange.bind(this, index, 'comment')}
                                                        value={pane.comment} placeholder="请输入表说明" maxLength="200"/>
                                                </Form.Item>
                                            </Col>
                                        </Row>
                                    </Form>

                                </Tabs.TabPane>
                            ))}
                        </Tabs>
                        <Row justify="center" align="center">
                            <Col span={6}>
                                <Select
                                    showSearch
                                    style={{width: 180}}
                                    placeholder="选择分组"
                                    optionFilterProp="children"
                                    onChange={this.handleSelectChange}
                                    value={this.state.selectValue}
                                    filterOption={(input, option) =>
                                        option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                    }>
                                    {
                                        this.state.codeRoots.map((item, index) => {
                                            return (
                                                <Select.Option data={item} value={item.id}>{item.name}</Select.Option>
                                            )
                                        })
                                    }
                                </Select>
                            </Col>
                            <Col span={18}>
                                <Checkbox.Group>
                                    {
                                        groups.map((item, index) => {
                                            return (
                                                <Checkbox onChange={this.onCodeGenCheckChange} checked={item.checked}
                                                          data={item} value={item.id}>{item.name}</Checkbox>
                                            )
                                        })
                                    }
                                </Checkbox.Group>
                            </Col>
                        </Row>
                    </>
                ), {
                    title: '代码生成',
                    props: {width: '70%', bodyStyle: {maxHeight: 580, overflow: 'auto'}},
                    okHandler: this._submitCodeGenModalForm
                })}

                {this.renderModal(pathForm, this.renderSpin(
                    <GenPathForm ref={(o) => this.pathForm = o}/>
                ), {
                    title: '选择生成目录',
                    okHandler: () => {
                        if (this.pathForm) {
                            this.pathForm.validateFormFields().then((values) => {
                                this.currentCheckItem.basePackage = values.basePackage;
                                this.currentCheckItem.outputPath = values.outputPath;
                                this.closeModal(pathForm)
                            });
                        }
                    }
                })}
                {this.renderModal(selectDirForm, this.renderSpin(
                    <DirectoryTree/>
                ), {
                    title: '选择目录',
                    okHandler: this._submitCodeGenModalForm
                })}

                {this.renderModal(previewForm, this.renderSpin(
                    <>
                        <CodeMirror
                            value={this.state.previewCode}
                            height="500px"
                            extensions={[javascript({jsx: true})]}
                        />
                        <Row justify="center" align="center">
                            <Col span={6}>
                                <Select
                                    showSearch
                                    style={{width: 180}}
                                    placeholder="选择分组"
                                    optionFilterProp="children"
                                    onChange={this.handleSelectChange}
                                    value={this.state.selectValue}
                                    filterOption={(input, option) =>
                                        option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                                    }>
                                    {
                                        this.state.codeRoots.map((item, index) => {
                                            return (
                                                <Select.Option data={item} value={item.id}>{item.name}</Select.Option>
                                            )
                                        })
                                    }
                                </Select>
                            </Col>
                            <Col span={18}>
                                <Tabs
                                    onChange={this.onChange}
                                    activeKey={activeKey}
                                >
                                    {groups.map(pane => (
                                        <Tabs.TabPane tab={pane.name} key={pane.id} closeable={false}>
                                            <Radio.Group onChange={this.onPreviewCheckChange}
                                                         value={this.state.radioValue}>
                                                {
                                                    pane.templates.map((item, index) => {
                                                        return (
                                                            <Radio data={item} value={item.id}>{item.display}</Radio>
                                                        )
                                                    })
                                                }
                                            </Radio.Group>
                                        </Tabs.TabPane>
                                    ))}
                                </Tabs>

                            </Col>
                        </Row>
                    </>
                ), {
                    title: tableName + '代码预览',
                    props: {width: '100%', bodyStyle: {maxHeight: 780, overflow: 'auto'}},
                    okHandler: this._submitCodeGenModalForm
                })}
            </div>
        )
    }


    showDoingIndicator(text, options = {}) {
        this.showSpin('处理中...');
    }

    closeLoadingIndicator() {
        this.closeSpin();
    }
}





